package edu.compila.client.api;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SimplePanel;

@SuppressWarnings("unchecked")
public class HistoryManager implements ValueChangeHandler<String> {

	private Map<String, Tela> telas = new HashMap<String, Tela>();
	private Tela atual; 
	private HashMap<String,String> paramAtual;
	private SimplePanel mainPanel;
	
	public HistoryManager(SimplePanel mainPanel) {
		History.addValueChangeHandler(this);
		this.mainPanel = mainPanel;
	}

	public void adicionar(Tela tela) {
		if(!telas.containsValue(tela)){
			telas.put(tela.getToken(), tela);
		} else {
			Window.alert("A tela já foi adicionada.");
		}
	}

	public void exibir(String token) {
		
		atual = telas.get(token);
		atual.createWidget();
		atual.setVisible(true);

		mainPanel.setWidget(atual);
		if (atual.getWidget() instanceof HasParam) {
			((HasParam) atual.getWidget()).set(paramAtual);
		}

	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {

		String historyToken = getHistoryToken(event.getValue());
		try {
			if (telas.containsKey(historyToken)) {
				//paramAtual = getHistoryTokenParameters(event.getValue());
				exibir(historyToken);
			} else {
				Window.alert("Url não registrada, tente novamente.");
			}
		} catch (IndexOutOfBoundsException e) {
			Window.alert("Url inválida, tente novamente.");
		}

	}

	private String getHistoryToken(String historyToken) {

		// skip if there is no question mark
		if (!historyToken.contains("?")) {
			return historyToken;
		}

		// get just the historyToken/anchor tag
		String[] arStr = historyToken.split("\\?");
		historyToken = arStr[0];

		return historyToken;
	}

	@SuppressWarnings("unused")
	private HashMap getHistoryTokenParameters(String historyToken) {

		// skip if there is no question mark
		if (!historyToken.contains("?")) {
			return null;
		}

		// ? position
		int questionMarkIndex = historyToken.indexOf("?") + 1;

		// get the sub string of parameters var=1&var2=2&var3=3...
		String[] arStr = historyToken.substring(questionMarkIndex,
				historyToken.length()).split("&");
		HashMap params = new HashMap();
		for (int i = 0; i < arStr.length; i++) {
			String[] substr = arStr[i].split("=");
			params.put(substr[0], substr[1]);
		}
		return params;
	}

}
